package sk.marek.barak.server;

import java.util.Date;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import sk.marek.barak.client.UserInformation;
import sk.marek.barak.shared.Util;

public class UserInformationGAEDAO implements UserInformationDAO {


	@Override
	public UserInformation getUser(String userID){
		Entity entity = getUserEntity(userID);
		UserInformation userInfo = new UserInformation();
		if(entity!=null){
		userInfo.setBirthDate(new Date(entity.getProperty("date").toString()));
		userInfo.setName(entity.getProperty("nickName").toString());
		userInfo.setUserID(userID);
		}
		
		return userInfo;
		
	}
	@Override
	public void saveUser(UserInformation user) {
		saveUserEntity(user);
		
	}
	
	private Entity getUserEntity(String id){
		Key key = KeyFactory.createKey("UserInfo",id);
	  	return Util.findEntity(key);
	}
	
	private void saveUserEntity(UserInformation user){
		Entity userInfo = getUserEntity(user.getUserID());
		if(userInfo==null)
			userInfo = new Entity("UserInfo",user.getUserID());
		
		userInfo.setProperty("nickName", user.getName());
		userInfo.setProperty("date", user.getBirthDate().toString());
		Util.persistEntity(userInfo);
		
	}

	@Override
	public UserInformation getCurentUserInformation() {
		UserService userService = UserServiceFactory.getUserService();
		User curentUser = userService.getCurrentUser();
		UserInformation curentUserInformation = new UserInformation();
		Key key = KeyFactory.createKey("UserInfo",curentUser.getUserId());
		Entity entity = Util.findEntity(key);
		
		if(entity!=null){
		curentUserInformation.setBirthDate(new Date(entity.getProperty("date").toString()));
		curentUserInformation.setName(entity.getProperty("nickName").toString());
		curentUserInformation.setUserID(curentUser.getUserId());
		
		}else{
			curentUserInformation.setBirthDate(new Date());
			curentUserInformation.setName(curentUser.getNickname());
			curentUserInformation.setUserID(curentUser.getUserId());
			saveUserEntity(curentUserInformation);
		}
		return curentUserInformation;
	}

}
